const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  avatar: {
    type: String,
    required: function () {
      return this.role === 'user'; // 仅对普通用户必填
    },
    default: function () {
      return this.role === 'admin' ? 'default_admin_avatar.png' : undefined;
    }
  },
  phone: {
    type: String,
    required: true
  },
  studentId: {
    type: String,
    required: function () {
      return this.role === 'user'; // 仅对普通用户必填
    },
    unique: true,
    sparse: true // 允许空值存在多个，避免唯一性冲突
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  status: {
    type: String,
    enum: ['normal', 'muted', 'banned'],
    default: 'normal'
  },
  statusReason: {
    type: String,
    default: ''
  },
  statusUpdatedAt: {
    type: Date
  },
  statusUpdatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// 密码加密中间件
userSchema.pre('save', async function (next) {
  if (this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 10);
  }
  next();
});

const User = mongoose.model('User', userSchema);
module.exports = User; 